import ai from '@/lib/ai';
import { getSession } from '@/lib/auth';
import { db } from '@/lib/db';
import { baseProcedure, createTRPCRouter } from '@/lib/trpc/init';
import { BizError, ErrorCode } from '@/service/error';
import { socketMessageSchema } from '@/service/type/socket';
import { z } from 'zod';

export const shop = createTRPCRouter({
  getShop: baseProcedure.query(async () => {
    const session = await getSession();
    if (!session?.user)
      throw new BizError(ErrorCode.Unauthorized, '用户未登录');
    return await db.query.shop.findFirst({
      where: (shop, { eq }) => eq(shop.userId, session.user.id),
    });
  }),
  genAiReply: baseProcedure
    .input(z.array(socketMessageSchema))
    .query(async ({ input: messages }) => {
      const text = await ai.genText([
        {
          role: 'system',
          content:
            '现在这里是一个外卖系统的在线客服聊天界面，商铺需要对用户进行一些回答。请根据以下消息记录为商铺客服生成三条可选回复。要求：每条回复在50字以内，回复之间用$符号分隔，不含其他额外字符。',
        },
        {
          role: 'user',
          content: messages
            .map(
              (m) =>
                `${m.user.role === 'user' ? '用户 - ' : '商铺 - '}${m.user.name} 说： ${m.content}`,
            )
            .join('\n'),
        },
      ]);
      return text
        .split('$')
        .map((r) => r.trim())
        .slice(0, 3);
    }),
});
